package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseRestartDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.EmployeeLoanContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

public class ShowEmployeePaymentFragment extends EmployeePaymentFragment {
  public static final String EXTRA_EMPLOYEELOANContent =
      "com.isunland.managesystem.ui.EXTRA_EMPLOYEELOANContent";
  protected static final String TAG = EmpoyeeLoanDetailFragment.class.getName();
  private static final int REQUEST_DELETE = 0;
  private static final int REQUEST_ALTER = 1;// 修改
  private static final int REQUEST_RESATRT = 2;//重新启动
  private static final int REQUEST_SATRT = 3;//启动
  private static final int REQUEST_STOP = 4;//终止
  private EmployeeLoanContent mEmployeeLoanContent;
  private String mType = "mobile";// 固定为mobile
  private String mId;// 信息id
  private String mDataStatus;// 数据状态

  @Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mEmployeeLoanContent =
        (EmployeeLoanContent) getArguments().getSerializable(EXTRA_EMPLOYEELOANContent);
    mId = mEmployeeLoanContent.getId();
    mDataStatus = mEmployeeLoanContent.getDataStatus();
    LogUtil.i("mrunId===" + mEmployeeLoanContent.getRunId());
  }

  // 创建菜单
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_employee_loan, menu);
    // menu.getItem(1).setVisible(false)
    // .setEnabled(false);

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override protected void setTitle() {
    ((BaseVolleyActivity) getActivity()).getSupportActionBar()
        .setTitle(R.string.employeeRepaymentApply);
  }

  @Override protected void initData() {

    mCertificateNoRepayment.setText(mEmployeeLoanContent.getCertificateNo());// 单据编号
    mExpenseDescRepayment.setText(mEmployeeLoanContent.getExpenseDesc());// 费用摘要
    mSumBorrowRepayment.setText(mEmployeeLoanContent.getSumBorrow());// 当前借款合计
    mPoutAmountRepayment.setText(mEmployeeLoanContent.getInAmount());// 还款金额
    mLoanPersonRepayment.setText(mEmployeeLoanContent.getDraweeName());// 还款人
    mLoanProposerRepayment.setText(mEmployeeLoanContent.getRegStaffName());// 申报人
    mLoanDateRepayment.setText(mEmployeeLoanContent.getApplyTime());// 申报日期
    mRepayDateRepayment.setText(mEmployeeLoanContent.getOccurDate());// 还款日期
    mRepayTypeRepayment.setText(mEmployeeLoanContent.getPayModeName());// 还款方式
    // 还款方式
    // mRepayTypeRepayment.setText(mEmployeeLoanContent.getPayModeCode());//还款方式编码
    mExpenseDescRepayment.setEnabled(false);// 费用摘要
    mPoutAmountRepayment.setEnabled(false);// 还款金额
    mIbRepayDateRepayment.setVisibility(View.GONE);
    mIbRepayTypeRepayment.setVisibility(View.GONE);

    //开户行
    etpayeeBank.setText(mEmployeeLoanContent.getPayeeBank());
    etpayeeAccname.setText(mEmployeeLoanContent.getPayeeAccname());
    etpayeeAccount.setText(mEmployeeLoanContent.getPayeeAccount());
    etpayeeBank.setEnabled(false);
    etpayeeAccname.setEnabled(false);
    etpayeeAccount.setEnabled(false);
    //附件
    if (mEmployeeLoanContent.getFileOriginalName() == null || TextUtils.isEmpty(
        mEmployeeLoanContent.getFileOriginalName())) {
      //			mEmployeeLoanContent.setFileOriginalName("");
      mTvExtra.setVisibility(View.GONE);
      mIvExtra.setVisibility(View.GONE);
    } else {
      mTvExtra.setText(mEmployeeLoanContent.getFileOriginalName());
      mIvExtra.setVisibility(View.GONE);
      //点击附件名，下载附件
      mTvExtra.setOnClickListener(new OnClickListener() {

        @Override public void onClick(View v) {
          ExtraDownLoadDialogFragment dialog =
              ExtraDownLoadDialogFragment.newInstance("", mEmployeeLoanContent.getFilePath());
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.show(fm, "");
        }
      });
    }
  }

  // 菜单点击事件
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        break;

      // 修改
      case R.id.menu_item_alter:
        if ("new".equals(mDataStatus) || "abort".equals(mDataStatus)) {
          //				Intent costIntent = new Intent(getActivity(),EmployeePaymentActivity.class);
          //				costIntent.putExtra(EditEmployeePaymentFragment.EXTRA_VALUE,mEmployeeLoanContent);
          //				costIntent.putExtra(EmployeePaymentActivity.EXTRA_TYPE,EmployeePaymentActivity.EXTRA_EDITCONTENTTYPE);
          //				startActivityForResult(costIntent, REQUEST_ALTER);

          Intent costIntent = new Intent(getActivity(), EditEmployeePaymentActivity.class);
          costIntent.putExtra(EditEmployeePaymentFragment.EXTRA_VALUE, mEmployeeLoanContent);
          //				costIntent.putExtra(EmployeePaymentActivity.EXTRA_TYPE,EmployeePaymentActivity.EXTRA_EDITCONTENTTYPE);
          startActivityForResult(costIntent, REQUEST_ALTER);
        } else {
          Toast.makeText(getActivity(), R.string.draftOrAbort, Toast.LENGTH_SHORT).show();
        }
        break;
      // 删除
      case R.id.menu_item_delete:
        if ("new".equals(mDataStatus) || "abort".equals(mDataStatus)) {

          showDialog(REQUEST_DELETE);
        } else {
          Toast.makeText(getActivity(), R.string.draftOrAbort, Toast.LENGTH_SHORT).show();
        }
        break;
      // 启动流程,草稿状态才可以启动
      case R.id.menu_item_startup:
        if ((mEmployeeLoanContent.getRunId()).equals("0")) {
          //			if ("new".equals(mDataStatus)) {
          showDialog(REQUEST_SATRT);
        } else if ("abort".equals(mDataStatus)) {

          showDialog(REQUEST_RESATRT);
        } else {
          Toast.makeText(getActivity(), R.string.ifstartup, Toast.LENGTH_SHORT).show();
        }
        break;
      //终止流程
      case R.id.menu_item_stop:
        //			Intent i=new Intent(getActivity(), StopTaskActivity.class);
        //			i.putExtra(StopTaskFragment.EXTRA_RUNID, mEmployeeLoanContent);
        //			startActivityForResult(i, REQUEST_STOP);
        if ("new".equals(mDataStatus)) {
          Toast.makeText(getActivity(), R.string.no_start, Toast.LENGTH_SHORT).show();
        } else if ("abort".equals(mDataStatus) || "checkPass".equals(mDataStatus) || DataStatus.PAID
            .equals(mDataStatus) || DataStatus.DOCUMENT.equals(mDataStatus)) {

          Toast.makeText(getActivity(), R.string.no_restart, Toast.LENGTH_SHORT).show();
        } else {
          showDialog(REQUEST_STOP);
        }
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyStop() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("runId", mEmployeeLoanContent.getRunId());
    LogUtil.i("终止流程params====" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i("终止流程====" + arg0);
        try {
          MyUtils.dismissDialog();
          //解析
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), result.getMessage().toString(), Toast.LENGTH_SHORT)
                .show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          Toast.makeText(getActivity(), R.string.wrong_data, Toast.LENGTH_SHORT).show();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  /**
   * 显示时间对话框
   *
   * @param requestCode 请求码
   * @param date 对话框初始显示时间
   */
  public void showDialog(int requestCode) {
    DialogFragment dialog = null;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (requestCode) {
      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        break;

      case REQUEST_RESATRT:
        dialog =
            BaseRestartDialogFragment.newInstance(R.string.restart_message, R.string.restart_title);

        break;
      case REQUEST_SATRT:
        dialog =
            BaseRestartDialogFragment.newInstance(R.string.start_up_hint, R.string.restart_title);

        break;
      case REQUEST_STOP:
        dialog = BaseRestartDialogFragment.newInstance(R.string.stop_hint, R.string.restart_title);

        break;
      default:
        break;
    }
    dialog.setTargetFragment(ShowEmployeePaymentFragment.this, requestCode);
    dialog.show(fm, "");
  }

  // 终止流程重新启动
  private void volleyReStart() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RESTART_UP);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("runId", mEmployeeLoanContent.getRunId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          //重新启动时的错误log日志
          LogUtil.i(workProcess.getMessage().toString());
          ToastUtil.show(R.string.failstartup);
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          volleyStart();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  // 启动流程方法
  private void volleyStart() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_START_UP);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("isList", "1");
    params.put("id", mEmployeeLoanContent.getId());
    params.put("recFlowKey", mEmployeeLoanContent.getFlowFlag());
    params.put("certificateCode", mEmployeeLoanContent.getCertificateCode());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {

          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          //					LogUtil.isSaveLog=true;
          //重新启动时的错误log日志
          LogUtil.e(workProcess.getMessage().toString());
          //					LogUtil.isSaveLog=false;
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  private void postDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE);

    HashMap<String, String> borrow = new HashMap<String, String>();
    borrow.put("type", mType);
    borrow.put("id", mId);
    if (!"0".equals(mEmployeeLoanContent.getRunId())) {
      borrow.put("runId", mEmployeeLoanContent.getRunId());
    }
    LogUtil.i("borrowParams===" + borrow.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, borrow, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        LogUtil.i(TAG, "response=" + arg0);
        SuccessMessage[] result = new Gson().fromJson(arg0, SuccessMessage[].class);
        SuccessMessage success = result[0];
        if (null == success || null == success.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = success.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_DELETE) {

      postDelete();// 删除

      return;
    }
    if (requestCode == REQUEST_SATRT) {

      volleyStart();

      return;
    }
    if (requestCode == REQUEST_RESATRT) {

      // 终止流程重新启动
      volleyReStart();
      return;
    }
    if (requestCode == REQUEST_ALTER) {

      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();

      return;
    }
    if (requestCode == REQUEST_STOP) {

      //			getActivity().setResult(Activity.RESULT_OK);
      //			getActivity().finish();
      volleyStop();

      return;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  // fragment之间传值
  public static ShowEmployeePaymentFragment newInstance(EmployeeLoanContent item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_EMPLOYEELOANContent, item);

    ShowEmployeePaymentFragment fragment = new ShowEmployeePaymentFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
